//
//  DNUserManager.m
//  DanoneEA
//
//  Created by Senela on 16/10/20.
//  Copyright © 2016年 翔傲科技. All rights reserved.
//

#import "DNUserManager.h"
#import "NSDate+Utils.h"

#import "DNCryingManager.h"
#import "DNStoolManager.h"
#import "DNFeedingManager.h"

#import "TTIViewController.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <AFNetworkReachabilityManager.h>

#import "Reachability.h" 
#import "NSDate+Utils.h"

@interface DNUserManager()
{
    NSDate    *lastVisitDate;
    
    NSDate    *startAppDate;
}
@end

@implementation DNUserManager

@synthesize lastVisitType = _lastVisitType;

+ (instancetype)sharedInstance {
    static DNUserManager *sharedInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

#pragma mark - Public methods

-(void) initSystemInformationOnce{
    
    //初始化数据库表，只初始化一次
    NSString * bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
    NSString * appFirstStartOfVersionKey = [NSString stringWithFormat:@"first_start_%@",bundleVersion];
    NSNumber * alreadyStartedOnVersion = [[DNUserManager sharedInstance] getValueFromDefaultWithKey:appFirstStartOfVersionKey];
    
    if(!alreadyStartedOnVersion || [alreadyStartedOnVersion boolValue] == NO){
        
        DDLogVerbose(@"initSystemInformationOnce ...");
        // init database once: drop tables,create table structure
        [[DNUserManager sharedInstance] setValueInDefault:[NSNumber numberWithBool:YES] withKey:appFirstStartOfVersionKey];
        
        [ [DNDataBase shareInstance] initDBTable];
        
    }
}
- (void)resetCurrentVCType
{
    UIViewController *currentVC = [[DNUserManager sharedInstance] getCurrentVC];
    if([currentVC isKindOfClass:[TTIViewController class]])
    {
        TTIViewController *VC = (TTIViewController *)currentVC;
        [self setLastVisitType:VC.type];
    }
}

-(void)printDeviceInfo
{
    //设备名称
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    DDLogVerbose(@"Device type: %@",deviceName );
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    DDLogVerbose(@"os version: %@", phoneVersion);
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    DDLogVerbose(@"Model version: %@",phoneModel );
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 当前应用名称
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    DDLogVerbose(@"Application name：%@",appCurName);
    // 当前应用软件版本  比如：1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    DDLogVerbose(@"Application version:%@",appCurVersion);
}

-(void)synchronousLocalDataToServer
{
    __block NSUInteger lastNetworkStatus; // app network status
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    lastNetworkStatus = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
    if(lastNetworkStatus != 0 )
//        [self synchronousLocalData];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
       
        // Broken network reconnection
        if( lastNetworkStatus < 1 &&
           (status == AFNetworkReachabilityStatusReachableViaWWAN
            || status == AFNetworkReachabilityStatusReachableViaWiFi))
        {
//            [self synchronousLocalData];
        }
        
        lastNetworkStatus = status;
    }];
    
    
    
    
    
}

-(NSString  *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

/**
 *  Set key and value value in NSUserDefaults
 *
 *  @param value
 *  @param key
 *
 */
-(void)setValueInDefault:(id)value withKey:(NSString *)key
{
    NSData *object = [NSKeyedArchiver archivedDataWithRootObject:value];
    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
 
/**
 *  According to the key to get the value in NSUserDefaults
 *
 *  @param key
 *
 *  @return
 */
-(id)getValueFromDefaultWithKey:(NSString *)key
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    id value = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return value;
}

#pragma mark - Private methods
-(void)synchronousLocalData
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //同步函数
    dispatch_sync(queue, ^{
        
        [[DNStoolManager sharedInstance] synchronousSpittingData];
        [[DNCryingManager sharedInstance] synchronousCryingData];
        [[DNFeedingManager sharedInstance] synchronousFeedingData]; 
    });

}


-(void)testForSaveCryingInfo
{
    DNCryingModel *cryingInfo = [[DNCryingModel alloc] init];
    cryingInfo.appId = [NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]];
    
    //TODO: format to be confirm
    cryingInfo.ddat = [NSDate currentTimeString];
    cryingInfo.timeOfDay = TimeOfDay_Morning;
    cryingInfo.cryInyn = @"Y";
    cryingInfo.crySttime = @"11:00";
    cryingInfo.cryEntime = @"12:00";
    
    [[DNCryingManager sharedInstance] addDiary:cryingInfo];
}

- (UIViewController *)getCurrentVC
{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if([nextResponder  isKindOfClass:[MMDrawerController class]])
    {
        MMDrawerController *tempVC = (MMDrawerController*)appRootVC;
        nextResponder = tempVC.centerViewController;
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]] )
    {
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]])
    {
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    return result;
}

/**
 *  Statistics of each module time-consuming
 *
 *  @param lastVisitType The current page belongs to the module
 */
-(void)setLastVisitType:(ModuleType)lastVisitType
{
    // Exit the app to the background, stop timing, and reset the lastVisitType state to ModuleType_None
    
    NSInteger time;
    if(_lastVisitType != ModuleType_None && lastVisitType == ModuleType_None)
    {
        time = [[NSDate date] timeIntervalSince1970] - [lastVisitDate timeIntervalSince1970];
     [[DNTimeConsumeDao shareInstance] appendTime:time byType:_lastVisitType dateStr:[NSDate currentTimeString]];
        DDLogVerbose(@"last type: %lu  visittime: %ld", (unsigned long)_lastVisitType, (long)time);
        _lastVisitType = lastVisitType;
        lastVisitDate = nil;
        
        
        time = [[NSDate date] timeIntervalSince1970] - [startAppDate timeIntervalSince1970];
        startAppDate = nil;
        [[DNTimeConsumeDao shareInstance] appendTime:time byType:ModuleType_APP dateStr:[NSDate currentTimeString]];
        
    }
    //Re-enter the app, reset the current lastVisitType status
    else if(_lastVisitType == ModuleType_None && lastVisitType != ModuleType_None)
    {
        
        lastVisitDate = [NSDate date];
        _lastVisitType = lastVisitType;
        
        DDLogVerbose(@"start current type: %lu", (unsigned long)_lastVisitType);
        
        startAppDate = [NSDate date];
    }
    //Switching in one module, not for processing
    else if(lastVisitType == _lastVisitType)
        return;
    // Switch the module and restart the timer
    else
    {
        
            time = [[NSDate date] timeIntervalSince1970] - [lastVisitDate timeIntervalSince1970];
            [[DNTimeConsumeDao shareInstance] appendTime:time byType:_lastVisitType dateStr:[NSDate currentTimeString]];
         
        
        DDLogVerbose(@"last type: %lu  visittime: %ld", (unsigned long)_lastVisitType, (long)time);
        
        lastVisitDate = [NSDate date];
        _lastVisitType = lastVisitType;
        DDLogVerbose(@"current type: %lu", (unsigned long)_lastVisitType);
    }
    
    
    
}

@end
